<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">
      <el-tab-pane label="所有订单" name="all">
        <div class="filter-container">
          <el-input
            v-model="listQuery.orderId"
            placeholder="订单号"
            style="width: 200px;"
            class="filter-item"
            clearable
          />
          <el-select
            v-model="listQuery.status"
            placeholder="订单状态"
            clearable
            style="width: 130px"
            class="filter-item"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-date-picker
            v-model="listQuery.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="filter-item"
            style="width: 300px"
          />
          <el-button type="primary" class="filter-item" @click="handleFilter">
            搜索
          </el-button>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="已支付订单" name="paid">
        <div class="filter-container">
          <el-input
            v-model="listQuery.orderId"
            placeholder="订单号"
            style="width: 200px;"
            class="filter-item"
            clearable
          />
          <el-select
            v-model="listQuery.paidStatus"
            placeholder="已支付订单状态"
            clearable
            style="width: 130px"
            class="filter-item"
          >
            <el-option label="待发货" :value="0" />
            <el-option label="已发货" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
          <el-date-picker
            v-model="listQuery.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="filter-item"
            style="width: 300px"
          />
          <el-button type="primary" class="filter-item" @click="handleFilter">
            搜索
          </el-button>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="未支付订单" name="unpaid">
        <div class="filter-container">
          <el-input
            v-model="listQuery.orderId"
            placeholder="订单号"
            style="width: 200px;"
            class="filter-item"
            clearable
          />
          <el-date-picker
            v-model="listQuery.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="filter-item"
            style="width: 300px"
          />
          <el-button type="primary" class="filter-item" @click="handleFilter">
            搜索
          </el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <el-card class="order-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-value">{{ orderCount }}</div>
            <div class="stat-label">总订单数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-value">{{ pendingCount }}</div>
            <div class="stat-label">待发货</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-value">{{ shippedCount }}</div>
            <div class="stat-label">已发货</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-value">¥{{ totalAmount }}</div>
            <div class="stat-label">总销售额</div>
          </div>
        </el-col>
      </el-row>
    </el-card>
    
    <el-table
      v-loading="listLoading"
      :data="filteredList"
      element-loading-text="Loading..."
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="订单号" width="180">
        <template #default="scope">
            
          {{ scope.row.order_id }}
        </template>
      </el-table-column>
      <el-table-column label="用户名" width="120">
        <template #default="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="金额" width="100" align="center">
        <template #default="scope">
          ¥{{ Number(scope.row.totalprice).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="图书数量" width="100" align="center">
        <template #default="scope">
          {{ getTotalBooks(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" width="120" align="center">
        <template #default="scope">
          {{ scope.row.paymentMethod || '在线支付' }}
        </template>
      </el-table-column>
      <el-table-column label="下单时间"  align="center">
        <template #default="scope">
          {{ formatDate(scope.row.orderDate) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" >
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleDetail(scope.row)"
          >
            详情
          </el-button>
          <el-button
            v-if="scope.row.status === '0'"
            size="small"
            type="success"
            @click="handleShip(scope.row)"
          >
            发货
          </el-button>
          <el-button
            v-if="scope.row.status === '0'"
            size="small"
            type="danger"
            @click="handleCancelOrder(scope.row)"
          >
            取消订单
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="listQuery.page"
        v-model:page-size="listQuery.limit"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>


    
    <!-- 发货对话框 -->
    <el-dialog
      title="订单发货"
      v-model="dialogShipVisible"
      width="500px"
    >
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px"
      >
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="shipForm.orderId" disabled />
        </el-form-item>
        <el-form-item label="快递公司" prop="expressCompany">
          <el-select v-model="shipForm.expressCompany" placeholder="请选择快递公司">
            <el-option label="顺丰速运" value="顺丰速运" />
            <el-option label="中通快递" value="中通快递" />
            <el-option label="圆通速递" value="圆通速递" />
            <el-option label="韵达快递" value="韵达快递" />
            <el-option label="申通快递" value="申通快递" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号" prop="trackingNumber">
          <el-input v-model="shipForm.trackingNumber" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogShipVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip">确认发货</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderAPI } from '../../utils/api'

// 获取路由信息
const route = useRoute()
const router = useRouter()

// 订单数据列表
const list = ref([])
const total = ref(0)
const listLoading = ref(true)

const dialogShipVisible = ref(false)
const currentOrder = ref({})
const shipFormRef = ref(null)
const activeTab = ref('all')



// 查询参数
const listQuery = reactive({
  page: 1,
  limit: 10,
  orderId: '',
  status: '',
  paidStatus: '',
  dateRange: []
})

// 发货表单
const shipForm = reactive({
  orderId: '',
  expressCompany: '',
  trackingNumber: ''
})

// 发货表单验证规则
const shipRules = {
  expressCompany: [{ required: true, message: '请选择快递公司', trigger: 'change' }],
  trackingNumber: [{ required: true, message: '请输入快递单号', trigger: 'blur' }]
}

// 订单状态选项
const statusOptions = [
  { label: '待发货', value: '0' },
  { label: '已发货', value: '1' },
  { label: '已取消', value: '2' }
]

// 计算属性：订单统计
const orderCount = computed(() => list.value.length)
const pendingCount = computed(() => list.value.filter(order => order.status === '0').length)
const shippedCount = computed(() => list.value.filter(order => order.status === '1').length)
const totalAmount = computed(() => {
  return list.value.reduce((total, order) => {
    return total + Number(order.totalprice || 0);
  }, 0).toFixed(2);
})

// 根据当前选项卡过滤列表
const filteredList = computed(() => {
  let filtered = [...list.value];
  
  // 根据订单号过滤
  if (listQuery.orderId) {
    filtered = filtered.filter(order => 
      order.order_id.toLowerCase().includes(listQuery.orderId.toLowerCase())
    );
  }
  
  // 根据标签页过滤
  if (activeTab.value === 'paid') {
    filtered = filtered.filter(order => order.status !== '2');
    
    // 根据已支付状态过滤
    if (listQuery.paidStatus !== '') {
      filtered = filtered.filter(order => order.status === String(listQuery.paidStatus));
    }
  } else if (activeTab.value === 'unpaid') {
    filtered = filtered.filter(order => order.status === '2');
  } else if (listQuery.status !== '') {
    // 全部订单页面，根据状态过滤
    filtered = filtered.filter(order => order.status === listQuery.status);
  }
  
  // 根据日期范围过滤
  if (listQuery.dateRange && listQuery.dateRange.length === 2) {
    const startDate = new Date(listQuery.dateRange[0]);
    startDate.setHours(0, 0, 0, 0);
    
    const endDate = new Date(listQuery.dateRange[1]);
    endDate.setHours(23, 59, 59, 999);
    
    filtered = filtered.filter(order => {
      const orderDate = new Date(order.orderDate);
      return orderDate >= startDate && orderDate <= endDate;
    });
  }
  
  // 更新总数
  total.value = filtered.length;
  
  // 分页
  const start = (listQuery.page - 1) * listQuery.limit;
  const end = start + listQuery.limit;
  
  return filtered.slice(start, end);
})

// 获取图书总数量
const getTotalBooks = (order) => {
  if (!order.books || !Array.isArray(order.books)) return 0;
  return order.books.reduce((total, book) => total + Number(book.num || 0), 0);
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '0':
      return 'primary'
    case '1':
      return 'success'
    case '2':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case '0':
      return '待发货'
    case '1':
      return '已发货'
    case '2':
      return '已取消'
    default:
      return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知日期';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

// 处理标签页切换
const handleTabClick = () => {
  listQuery.page = 1;
  if (activeTab.value === 'paid') {
    listQuery.status = '';
    listQuery.paidStatus = 0;  // 默认显示待发货
  } else if (activeTab.value === 'unpaid') {
    listQuery.status = '2';
    listQuery.paidStatus = '';
  } else {
    listQuery.status = '';
    listQuery.paidStatus = '';
  }
}

// 获取订单列表数据
const getList = async () => {
  listLoading.value = true;
  
  try {
    const res = await orderAPI.getList();
    if (res.code === 200) {
      list.value = res.data || [];
      total.value = list.value.length;
    } else {
      ElMessage.error(res.message || '获取订单列表失败');
    }
  } catch (error) {
    console.error('获取订单列表错误:', error);
    ElMessage.error('获取订单列表失败: ' + (error.message || '未知错误'));
  } finally {
    listLoading.value = false;
  }
}

// 处理分页大小改变
const handleSizeChange = (val) => {
  listQuery.limit = val;
}

// 处理页码变化
const handleCurrentChange = (val) => {
  listQuery.page = val;
}

// 处理搜索过滤
const handleFilter = () => {
  listQuery.page = 1;
}

// 查看订单详情
const handleDetail = (row) => {
  // 跳转到订单详情页面
  router.push(`/orders/detail/${row.order_id}`);
}

// 处理发货
const handleShip = (row) => {
  shipForm.orderId = row.order_id;
  shipForm.expressCompany = '';
  shipForm.trackingNumber = '';
  dialogShipVisible.value = true;
}

// 确认发货
const confirmShip = () => {
  shipFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await orderAPI.ship({
          orderId: shipForm.orderId,
          expressCompany: shipForm.expressCompany,
          trackingNumber: shipForm.trackingNumber
        });
        
        if (res.code === 200) {
          // 更新订单状态
          const index = list.value.findIndex(item => item.order_id === shipForm.orderId);
          if (index !== -1) {
            list.value[index].status = '1';
            list.value[index].expressCompany = shipForm.expressCompany;
            list.value[index].trackingNumber = shipForm.trackingNumber;
            list.value[index].shippingTime = new Date().toLocaleString();
            ElMessage.success('发货成功');
          }
          dialogShipVisible.value = false;
        } else {
          ElMessage.error(res.message || '发货失败');
        }
      } catch (error) {
        console.error('发货错误:', error);
        ElMessage.error('发货失败: ' + (error.message || '未知错误'));
      }
    }
  });
}

// 取消订单
const handleCancelOrder = (row) => {
  ElMessageBox.confirm('确定要取消此订单吗？此操作不可撤销。', '取消订单', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await orderAPI.cancel(row.order_id);
      if (res.code === 200) {
        // 更新订单状态
        const index = list.value.findIndex(item => item.order_id === row.order_id);
        if (index !== -1) {
          list.value[index].status = '2';
          ElMessage.success('订单已取消');
        }
      } else {
        ElMessage.error(res.message || '取消订单失败');
      }
    } catch (error) {
      console.error('取消订单错误:', error);
      ElMessage.error('取消订单失败: ' + (error.message || '未知错误'));
    }
  }).catch(() => {
    // 用户取消操作
  });
}

// 监听路由参数变化
watch(() => route.query.tab, (newTab) => {
  if (newTab) {
    activeTab.value = newTab;
    handleTabClick();
  }
}, { immediate: true });

// 页面加载时获取数据
onMounted(() => {
  // 从URL参数中获取初始标签
  const tabParam = route.query.tab;
  if (tabParam) {
    activeTab.value = tabParam;
    handleTabClick();
  }
  
  getList();
})
</script>

<style scoped>
.app-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.el-tabs {
  flex-shrink: 0;
}

.filter-container {
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  flex-shrink: 0;
}

.el-table {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  padding: 10px;
  text-align: right;
  background-color: #fff;
  flex-shrink: 0;
}

.order-detail {
  padding: 10px;
  max-height: 70vh;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-item {
  margin-bottom: 10px;
}

.detail-label {
  font-weight: bold;
  margin-right: 10px;
}

.order-summary {
  text-align: right;
  margin-top: 20px;
  padding: 10px 0;
  border-top: 1px dashed #ebeef5;
}

.summary-item {
  margin-bottom: 10px;
}

.amount {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.order-stats {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 15px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  margin-top: 5px;
  color: #606266;
}
</style>